<?php
/**
 * Created by PhpStorm.
 * User: Zhoujinda
 * Date: 2016/8/2
 * Time: 15:37
 */
namespace app\index\controller;

use app\index\controller\Alipay;
use app\common\api\PayOrderApi;
use app\shop\api\AlipayNotifyApi;
use app\common\api\ExchangeLogApi;

class AlipayDirect extends Alipay{

    private $alipay_config = [];
    public function __construct(){
        parent::__construct();
        //引入支付官方sdk
        vendor_old('alipay_notify',APP_PATH.'index/vendor/AlipayDirect/lib','.class.php');
        $this->alipay_config = $this->getAlipayDirectConfig();
        // dump($this->alipay_config);exit;
    }

    // private function slog($log, $type = '', $user = false){
    //     if($user==false)$user = 'xiao';
    //     vendor_old('XSocketlog',APP_PATH.'index/vendor/XSocketlog','.class.php');
    //     $socketlog = new \socketlog($user);
    //     $socketlog->send($log, $type);
    // }

    public function return_url(){
        addLog('AlipayDirect/return_url',$_GET,$_POST,'支付宝return_url',true);
        // $_POST = ["discount"=>"0.00","payment_type"=>"1","subject"=>"\u8ba2\u5355T1470125155U17P314","trade_no"=>"2016080221001004920281938681","buyer_email"=>"bierqi@163.com","gmt_create"=>"2016-08-02 16:06:04","notify_type"=>"trade_status_sync","quantity"=>"1","out_trade_no"=>"T1470125155U17P314","seller_id"=>"2088221673470288","notify_time"=>"2016-08-02 16:10:26","trade_status"=>"TRADE_SUCCESS","is_total_fee_adjust"=>"N","total_fee"=>"0.01","gmt_payment"=>"2016-08-02 16:06:07","seller_email"=>"mengwukids@163.com","price"=>"0.01","buyer_id"=>"2088202272162921","notify_id"=>"c224e9b0f24b8d625b3fe1ff9e5c1f9n3m","use_coupon"=>"N","sign_type"=>"RSA","sign"=>"G0Qn1xGotUqb0kM5gGxFz7P9Qjm0v\/CSvQkIDYFU7nIeH7g9iACP26Har+3cTp4N5IR5y11H9Q5xUXY2Mhji1rw0Guosc8iZgO2kWhYstzvhLhuKDGEZsmsSJksD2y1k60QEyHpKSqjXe1XUeuwwCHYl\/42O0OFqm5gV\/opq1fA="];
        $alipayNotify = new \AlipayNotify($this->alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        // echo 'verify';
        // dump($verify_result);
        // addLog('AlipayDirect/return_url',$_GET,$verify_result,'支付宝return_url',true);
        if($verify_result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代


            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号
            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];


            if($_POST['trade_status'] == 'TRADE_FINISHED') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知

                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
                // $this->slog('TRADE_FINISHED');
                 $this->log();
                $this->paySuccess($out_trade_no);
            }
            else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
                $this->log();
                $this->paySuccess($out_trade_no);
            }
            // $this->slog($_POST,'POST');

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            echo "success";		//请不要修改或删除

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }
        else {
            //验证失败
            echo "fail";

            //调试用，写文本函数记录程序运行情况是否正常
            //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
        }
    }


    private function paySuccess($out_trade_no){
        $prex = substr($out_trade_no,0,1);
        if($prex == 'T'){
            apiCall(PayOrderApi::SUCCESS,array($out_trade_no,1));
        }elseif($prex=='S'){
            apiCall(ExchangeLogApi::PAYBACK,array($out_trade_no));
        }

    }

    private function log(){

        $entity = array(
            'payment_type'        => $_POST['payment_type'],
            'subject'             => $_POST['subject'],
            'trade_no'            => $_POST['trade_no'],
            'buyer_email'         => $_POST['buyer_email'],
            'gmt_create'          => $_POST['gmt_create'],
            'notify_type'         => $_POST['notify_type'],
            'quantity'            => $_POST['quantity'],
            'out_trade_no'        => $_POST['out_trade_no'],
            'seller_id'           => $_POST['seller_id'],
            'notify_time'         => $_POST['notify_time'],
            'body'                => isset($_POST['body'])? $_POST['body']:'',
            'trade_status'        => $_POST['trade_status'],
            'is_total_fee_adjust' => $_POST['is_total_fee_adjust'],
            'total_fee'           => $_POST['total_fee'],
            'seller_email'        => $_POST['seller_email'],
            'use_coupon'          => $_POST['use_coupon'],
            'buyer_id'            => $_POST['buyer_id'],
            'notify_id'           => $_POST['notify_id'],
            'price'               => $_POST['price'],
            'sign_type'           => $_POST['sign_type'],
            'sign'                => $_POST['sign'],
            'gmt_payment'         => $_POST['gmt_payment']
        );

        $result = apiCall(AlipayNotifyApi::ADD,array($entity));
        // if(!$result['status']){
        //     LogRecord($result['info'],__FILE__.__LINE__);
        // }
    }
}